#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <errno.h>
#include <string.h>

using namespace std;

#define NUM 3

__thread int g_val=0;

int* p=nullptr;

string toHex(pthread_t tid)
{
    char arr[1024];
    snprintf(arr, sizeof(arr), "%p", tid);
    return arr;
}

void *ThreadRoutine(void *args)
{
    int a=11;
    p=&a;
    cout<<a<<":"<<&a<<endl;

    int cnt = 3;
    while (cnt--)
    {
        cout << "I'm thread :" << toHex(pthread_self()) 
        <<"my g_val is :"<<g_val<<endl;
        g_val++;
        sleep(1);
    }

    return nullptr;
}

int main()
{
    vector<pthread_t> vthd;
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, ThreadRoutine, nullptr);
        vthd.push_back(tid);
        usleep(10000);
    }

    sleep(1);

    // for (auto tid : vthd)
    // {
    //     pthread_detach(tid);
    // }

    cout<<"main thread"<<*p<<":"<<p<<endl;

    for (auto tid : vthd)
    {
        int n=pthread_join(tid, nullptr);
        if(n!=0)
        {
            cout<<strerror(n)<<endl;
        }
    }

    return 0;
}